﻿#ifndef BUSINESSFILE_H
#define BUSINESSFILE_H

#include <protocol/protocol.h>
#include <memory>
#include <hv/Channel.h>
#include <stdint.h>
#include <nlohmann/json.hpp>
#include <mutex>
class BusinessFile
{
public:
    // 删除拷贝构造函数和拷贝赋值操作符
    BusinessFile(BusinessFile const&) = delete;
    BusinessFile& operator=(BusinessFile const&) = delete;
    // 提供一个全局唯一的接口
    static BusinessFile& getInstance() {
        static BusinessFile instance;
        return instance;
    }

    // send file
    void recvDownloadRequest(std::shared_ptr<Protocol> protocol, const hv::SocketChannelPtr &channel);
    // receiver a block of a file
    void RecvConfirmOfFileBlock(std::shared_ptr<Protocol> protocol, const hv::SocketChannelPtr &channel);

    // send file list
    void sendFileList(std::shared_ptr<Protocol> protocol, const hv::SocketChannelPtr &channel);

    ///////////// 文件传输相关

    // receive a request of uploading file
    void recvUploadFileRequest(std::shared_ptr<Protocol> protocol, const hv::SocketChannelPtr& channel);
    // receive a file block transmission
    void recvFileBlock(std::shared_ptr<Protocol> protocol, const hv::SocketChannelPtr& channel);
    // transmiss end
    void recvEndFileTransmission(std::shared_ptr<Protocol> protocol, const hv::SocketChannelPtr& channel);

    ////////////// 维护文件传输任务

    // 删除一个用户相关的传输任务（上传与下载）
    void eraseUserTransfer(uint64_t userID);

    // 更新从客户端下载文件任务的id
    void updateDownloadID(uint64_t userID, uint64_t id);

    // 更新向客户端上传文件任务的id
    void updateUploadSyncPoint(uint64_t userID, uint64_t point);

    // 检查当前用户 是否有文件向客户端上传,true:当前有文件正在上传，false:当前无文件正在上传
    bool checkUpload(uint64_t userID);

    // 检查当前用户 是否有文件从客户端下载,true:当前有文件正在下载，false:当前无文件正在下载
    bool checkDownload(uint64_t userID);



    // get json of message
    static nlohmann::json getJsonOfMessage(std::shared_ptr<Protocol> protocol);

private:
    BusinessFile();

    struct Point {
        uint64_t uploadSyncPoint = -1;
        uint64_t downloadTaskId = -1;
    };

    // {上传到客户端 任务的syncpoint, 从客户端下载 任务的id}
    std::unordered_map<uint64_t, Point> userTransferTaskIds;

    // 锁
    std::mutex storeLock;

};

#endif // BUSINESSFILE_H
